package cn.edu.ecust.market.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;


/**
 * @author liao
 */
@Slf4j
@Component
public final class JwtUtil {

    private JwtUtil() {
    }

    private static final byte[] SECRET_KEY = new byte[256];

    /**
     * 生成token
     */
    public static String generateToken(Map<String, Object> claims, Long expire) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    /**
     * 解析token
     */
    public static Claims parserToken(String token) {
        if(token == null || "".equals(token)) {
            return null;
        }
        try {
            return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return null;
        }
    }

}
